<script setup lang="ts">
defineOptions({
  name: "baseInfo"
});

import { ref, reactive, onMounted, markRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import type { FormInstance, FormRules } from "px-ui";
import dayjs from "dayjs";
import { queryGasDeviceCode, queryGasDeviceInfo, getExecutorList } from "@/api/modules/operation";
import { queryUserList } from "@/api/modules/fab";
import { formatAccountName } from "@/utils/common";

const route = useRoute();
const router = useRouter();
const routerStore = useRouterStoreHook();

interface RuleForm {
  workOrderNo: string;
  deviceCode: string;
  location: string;
  position: string;
  executorList: Array<string>;
  startTime: string;
  endTime: string;
  createRemark: string;
}

interface ListItem {
  value: string;
  label: string;
  [key: string]: any;
}

interface Props {
  disabled: boolean;
  data: Record<string, any>;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  data: () => null
});

const baseInfoRuleForm = defineModel({
  type: Object,
  default: () => ({
    workOrderNo: "",
    deviceCode: "",
    location: "",
    position: "",
    executorList: [],
    startTime: "",
    endTime: "",
    createRemark: ""
  })
});

const emits = defineEmits(["change"]);
const deviceCodeOptions = ref<Array<ListItem>>([]);
const deviceCodeLoading = ref(false);
const executorOptions = ref<Array<ListItem>>([]);
const executorLoading = ref(false);
const baseInfoRuleFormRef = ref<FormInstance | null>(null);
const positionOptions = ["左", "右"];

const baseInfoRules = reactive<FormRules<RuleForm>>({
  workOrderNo: [{ required: route.query.type === "check" || route.query.type === "edit", message: "请输入工单号", trigger: ["blur", "change"] }],
  deviceCode: [{ required: true, message: "请选择设备编号", trigger: ["blur", "change"] }],
  location: [{ required: true, message: "", trigger: ["blur", "change"] }],
  position: [{ required: true, message: "请选择点位", trigger: ["blur", "change"] }],
  executorList: [{ required: true, message: "请选择责任人", trigger: ["blur", "change"] }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: ["blur", "change"] }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: ["blur", "change"] }],
  createRemark: [{ required: false, message: "请输入备注信息", trigger: ["blur", "change"] }]
});

const deviceCodeRemoteMethod = async (eqpId: string) => {
  deviceCodeOptions.value = [];
  if (eqpId) {
    deviceCodeLoading.value = true;
    const { subject: className } = routerStore;
    const categoryIds = [105];
    const modelId = 770;
    // facCode   一期  FAC_83abf9   二期  FAC_93abf6
    const facCode = localStorage.getItem("facCode");
    const systemCodes = facCode === "FAC_83abf9" ? ["SC707B19"] : facCode === "FAC_93abf6" ? ["SCF3F30D"] : [];
    const params = { eqpId, className, systemCodes, categoryIds, modelId };
    const res = await queryGasDeviceCode(params);
    deviceCodeOptions.value = res.map(item => ({ ...item, label: item.eqpId, value: item.eqpId }));
    deviceCodeLoading.value = false;
  }
};

const deviceCodeChangeHandler = async (val: string) => {
  if (!val) {
    baseInfoRuleForm.value.location = "";
    emits("change", {}, baseInfoRuleForm.value);
    return;
  }
  const t = deviceCodeOptions.value.find(item => item.value === val);
  if (t) {
    const { eqpId } = t;
    const res = await queryGasDeviceInfo({ eqpId });
    if (!res) return;
    const { positionNameAll = "", systemName: gasName = "" } = res;
    baseInfoRuleForm.value.location = positionNameAll;
    emits("change", { gasName }, baseInfoRuleForm.value);
  }
};

const executorRemoteMethod = async (realName: string) => {
  executorOptions.value = [];
  if (realName) {
    executorLoading.value = true;
    const page = 1;
    const pageSize = 9999;
    // const usernameLike = realName; //  账号查询
    // const params = { page, pageSize, usernameLike }; //  账号查询
    const realNameLike = realName; //  姓名查询
    const params = { page, pageSize, realNameLike }; //  姓名查询
    const res = await queryUserList(params);
    // const res = await getExecutorList({ realName });
    // executorOptions.value = res.map(item => ({ label: item.realName, value: item.userId }));
    executorOptions.value = res?.data?.map(({ userId: value, username = "", realName = "" }: any) => ({
      value,
      label: formatAccountName(username, realName)
    }));
    executorLoading.value = false;
  }
};

const startDisabledDateFn = (d: Date) => {
  const currentTimeStamp = Date.now();
  const timeStamp = new Date(d).getTime();
  if (timeStamp < currentTimeStamp - 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (timeStamp > currentTimeStamp + 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (baseInfoRuleForm.value.endTime && timeStamp > dayjs(baseInfoRuleForm.value.endTime).valueOf()) return true;
  return false;
};

const endDisabledDateFn = (d: Date) => {
  const currentTimeStamp = Date.now();
  const timeStamp = new Date(d).getTime();
  if (timeStamp < currentTimeStamp - 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (timeStamp > currentTimeStamp + 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (baseInfoRuleForm.value.startTime && timeStamp < dayjs(baseInfoRuleForm.value.startTime).valueOf()) return true;
  return false;
};

const validate = () => {
  return new Promise((resolve, reject) => {
    if (!baseInfoRuleFormRef.value) return reject(false);
    baseInfoRuleFormRef.value.validate(valid => {
      if (valid) {
        resolve(markRaw(baseInfoRuleForm.value));
      } else {
        reject(false);
      }
    });
  });
};

const reset = () => {
  if (!baseInfoRuleFormRef.value) return;
  baseInfoRuleFormRef.value.resetFields();
};

const init = async () => {
  baseInfoRuleFormRef.value.resetFields();
};

onMounted(async () => {
  await init();
});

defineExpose({
  baseInfoRuleFormRef,
  baseInfoRuleForm,
  validate,
  reset
});
</script>

<template>
  <px-form ref="baseInfoRuleFormRef" :model="baseInfoRuleForm" :rules="baseInfoRules" label-width="120px" class="base-info-form" status-icon>
    <px-row :gutter="24">
      <px-col v-if="route.query.type === 'check' || route.query.type === 'edit'" :span="8">
        <px-form-item label="工单号" prop="workOrderNo">
          <px-input v-model.trim="baseInfoRuleForm.workOrderNo" disabled clearable placeholder="请输入工单号" />
        </px-form-item>
      </px-col>
      <px-col :span="8">
        <px-form-item label="设备编号" prop="deviceCode">
          <px-select
            v-model="baseInfoRuleForm.deviceCode"
            :disabled="disabled"
            clearable
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            placeholder="请选择设备编号"
            :remote-method="deviceCodeRemoteMethod"
            :loading="deviceCodeLoading"
            @change="deviceCodeChangeHandler"
          >
            <px-option v-for="item in deviceCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>

      <px-col :span="8">
        <px-form-item label="设备地点" prop="location">
          <px-input v-model.trim="baseInfoRuleForm.location" disabled clearable placeholder="" />
        </px-form-item>
      </px-col>

      <px-col :span="8">
        <px-form-item label="点位" prop="position">
          <px-select v-model="baseInfoRuleForm.position" :disabled="disabled" clearable filterable placeholder="请选择点位">
            <px-option v-for="item in positionOptions" :key="item" :label="item" :value="item" />
          </px-select>
        </px-form-item>
      </px-col>

      <px-col :span="8">
        <px-form-item label="责任人" prop="executorList">
          <px-select
            v-model="baseInfoRuleForm.executorList"
            :disabled="disabled"
            multiple
            clearable
            filterable
            remote
            collapse-tags
            collapse-tags-tooltip
            remote-show-suffix
            placeholder="请选择责任人"
            :remote-method="executorRemoteMethod"
            :loading="executorLoading"
          >
            <px-option v-for="item in executorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>
      <px-col :span="8">
        <px-form-item label="开始时间" prop="startTime">
          <px-date-picker
            v-model="baseInfoRuleForm.startTime"
            :disabled="disabled"
            clearable
            type="datetime"
            :editable="false"
            format="YYYY/MM/DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="startDisabledDateFn"
            placeholder="请选择开始时间"
          />
        </px-form-item>
      </px-col>
      <px-col :span="8">
        <px-form-item label="结束时间" prop="endTime">
          <px-date-picker
            v-model="baseInfoRuleForm.endTime"
            :disabled="disabled"
            clearable
            type="datetime"
            :editable="false"
            format="YYYY/MM/DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            :disabled-date="endDisabledDateFn"
            placeholder="请选择结束时间"
          />
        </px-form-item>
      </px-col>
      <px-col :span="24">
        <px-form-item label="备注" prop="createRemark">
          <px-input
            v-model.trim="baseInfoRuleForm.createRemark"
            :disabled="disabled"
            :rows="2"
            type="textarea"
            maxlength="1000"
            show-word-limit
            clearable
            placeholder="请输入备注信息"
          />
        </px-form-item>
      </px-col>
    </px-row>
  </px-form>
</template>

<style lang="scss" scoped>
.base-info-form {
  box-sizing: border-box;
  padding: 16px;
  padding-bottom: 0;

  .px-form-item {
    .px-select {
      width: 100%;
    }

    :deep(.px-date-editor) {
      width: 100%;
    }
  }
}
</style>
